package com.jt.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.jt.provider.service.ResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.Console;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/provider")
@Slf4j
public class ProviderSentinelController {

    @GetMapping("/sentinel01")
    public String doSentinel01(){
        return "sentinel 01 test  ...";
    }

    @GetMapping("/sentinel02")
    public String doSentinel02(){
        return "sentinel 02 test  ...";
    }

    @Autowired
    private ResourceService resourceService;
    @GetMapping("/sentinel03")
    public String doSentinel03() throws InterruptedException {
        //请求链路中的资源访问
        //resourceService.doGetResource();
        //return "sentinel 03 test";
        return resourceService.doGetResource();
    }

    @GetMapping("/sentinel04")
    public String doSentinel04() throws InterruptedException {
        //请求链路中的资源访问
        //resourceService.doGetResource();
        //return "sentinel 03 test";
        return resourceService.doGetResource();
    }

    //AtomicLong 类支持线程安全的自增自减操作
    private AtomicLong atomicLong=new AtomicLong(1);
    @GetMapping("/sentinel05")
    public  String doSentinel05() throws InterruptedException {
        //获取自增对象的值,然后再加1
        long num=atomicLong.getAndIncrement();
        log.info("num=" +num);
        if(num%2==0){//模拟50%的慢调用比例
            Thread.sleep(200);
        }
        return "sentinel 05 test";
    }

    @GetMapping("/sentinel/findById")
    @SentinelResource("resource")
    public String doFindById(@RequestParam("id") Integer id){
        return "resource id is "+id;
    }

}
